package com.jaks.xpense;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.jaks.xpense.data.Expenses;
import com.jaks.xpense.data.entities.Expense;
import com.jaks.xpense.data.entities.PaymentType;
import com.jaks.xpense.data.entities.TableEntity;
import com.jaks.xpense.utils.Globals;

public class FilterExpensesActivity extends ListActivity {

	private Expenses expenses;
	private Cursor filteredExpenses;

	private int searchMode;
	private String expenseIds;
	private String from;
	private String to;
	private long paymentTypeId;
	private long[] selectedTagIds;

	private TextView totalView;

	private final static int SearchAll = 1;
	private final static int SearchByDates = 2;
	private final static int SearchByExpenseId = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		paymentTypeId = 0;
		filteredExpenses = null;
		expenses = new Expenses(this);
		setContentView(R.layout.filterexpenses);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {

			String ids = extras.getString("expenseIds");
			if (ids != null) {
				searchMode = SearchByExpenseId;
				expenseIds = ids;
			} else {
				searchMode = SearchByDates;

				String[] dates = extras.getStringArray("dates");
				from = dates[0];
				to = dates[1];
				selectedTagIds = extras.getLongArray(Globals.SelectedTagIds);
				paymentTypeId = extras.getLong("paymentType");
			}
		} else {
			searchMode = SearchAll;
		}
		totalView = (TextView) findViewById(R.id.searchTotal);
		totalView.setText(Globals.Empty);
	}

	@Override
	protected void onStart() {
		super.onStart();

		if (filteredExpenses == null) {

			if (searchMode == SearchByDates) {
				filteredExpenses = expenses.getFilteredExpenses(from, to, selectedTagIds, paymentTypeId);
			} else if (searchMode == SearchByExpenseId) {
				filteredExpenses = expenses.getFilteredExpenses(expenseIds);
			} else {
				filteredExpenses = expenses.readAll();
			}
			startManagingCursor(filteredExpenses);

			populate();
		}
		totalView.setText(Globals.toDecimalText(getTotal()));
	}

	private double getTotal() {
		double total = 0;
		if (filteredExpenses == null)
			return total;

		if ((filteredExpenses.getCount() > 0) && filteredExpenses.moveToFirst()) {

			do {
				double amount = filteredExpenses.getDouble(filteredExpenses.getColumnIndex(Expense.Amount));
				total += amount;
			} while (filteredExpenses.moveToNext());
		}

		return total;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		expenses.close();
	}

	private void populate() {

		String[] tableColumns = new String[] { Expense.ExpenseDate, Expense.Amount, Expense.Comments,
		    PaymentType.Name };
		int[] columnNames = new int[] { R.id.rowDate, R.id.rowAmount, R.id.rowComments,
		    R.id.rowPaymentType };

		setListAdapter(new SimpleCursorAdapter(this, R.layout.tile_expense_row, filteredExpenses,
		    tableColumns, columnNames) {
			@Override
			public void setViewText(TextView view, String text) {
				super.setViewText(view, formatText(view, text));
			}
		});
	}

	private String formatText(TextView view, String text) {
		switch (view.getId()) {
			case R.id.rowAmount:
				double amount = filteredExpenses.getDouble(filteredExpenses.getColumnIndex(Expense.Amount));
				return Globals.toDecimalText(amount);
		}
		return text;
	}

	private void editExpense(long id) {
		Intent intent = new Intent(this, EditExpenseActivity.class);
		intent.putExtra(TableEntity.Id, id);
		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK)
			return;
		filteredExpenses.requery();
		totalView.setText(Globals.toDecimalText(getTotal()));
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position, long id) {
		super.onListItemClick(listView, view, position, id);

		editExpense(id);
	}
}
